#pragma once

namespace cm {
	namespace Windows {

class CButtonMenu : public CWindowImpl<CButtonMenu, CButton>
{
protected:
	UINT m_nID;
	CFont m_font;
public:
	CButtonMenu() : m_nID(0), m_font(NULL)
	{
	}
	
	// Set the resource ID of the menu to display
	inline void SetMenu(UINT nID) { m_nID = nID; }

	BEGIN_MSG_MAP(CButtonMenu)
		REFLECTED_COMMAND_CODE_HANDLER(BN_CLICKED, OnClick)
		DEFAULT_REFLECTION_HANDLER()
	END_MSG_MAP()

	LRESULT OnClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		// Do we have a menu?
		if (m_nID == 0)
			return 0;
		// Check the button
		if (GetCheck() == FALSE)
			SetCheck(TRUE);
		// Get the window rect
		CRect rect;
		GetWindowRect(&rect);
		// Create and load the popup menu
		CMenu menu;
		if (!menu.LoadMenu(m_nID))
			return 0;
		// Get the popup
		CMenuHandle menuPopup = menu.GetSubMenu(0);
		// Do we have the submenu?
		if (menuPopup == NULL)
			return 0;
		// Display
		menuPopup.TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,
			rect.right, rect.top, GetParent());
		// Check button off
		SetCheck(FALSE);
		// Done
		return 0;
	}

	BOOL SubclassWindow(HWND hWnd)
	{
		// Call base class
		BOOL bRet = CWindowImpl<CButtonMenu, CButton>::SubclassWindow(hWnd);
		// Initialise here
		if (bRet)
		{
			// Remove icon style
			if ((GetStyle() & BS_ICON) == BS_ICON)
				ModifyStyle(BS_ICON, 0);
			// Create the "Marlett" font
			if (m_font.m_hFont == NULL)
				m_font.CreatePointFont(100, _T("Marlett"));
			// Use the font?
			if (m_font.m_hFont)
			{
				SetFont(m_font);
				// Display the arrow
				SetWindowText(_T("4"));
			}
			else
			{
				// Default to a sensible char 
				SetWindowText(_T(">"));
			}
		}
		// Done
		return bRet;
	}
};

}}
